package com.polaris.live.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.coroutineScope
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.databinding.WidgetMagicLampBtnBinding
import com.polaris.live.net.payerService
import com.polaris.live.resp.back_resp.PayerLampProgressResp
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.widget.bubble.DownLoadFileUtil
import org.libpag.PAGFile

/**
 * 神灯按钮
 *
 * @author Created by 半仙 on 2024/7/23/023 16:07
 */
class MagicLampBtnView(context: Context, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {

    private val mBinding = WidgetMagicLampBtnBinding.inflate(LayoutInflater.from(context), this, true)

    private var mIsLifecycleRegistered = false//是否addObserver过

    private var mViewModel: BaseViewModel? = null
    private var mUserId: Long? = null
    private var mLifecycle: Lifecycle? = null


    private val copper = "static/lamp/icon/copper.pag" //铜pag
    private val silver = "static/lamp/icon/silver.pag" //银pag
    private val gold = "static/lamp/icon/gold.pag"    //金pag
    fun registerObserve(lifecycle: Lifecycle, viewModel: BaseViewModel, userId: Long) {
        mViewModel = viewModel
        mUserId = userId
        mLifecycle = lifecycle
        if (!mIsLifecycleRegistered) {
            mIsLifecycleRegistered = true
            lifecycle.addObserver(object : LifecycleEventObserver {
                override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                    if (event == Lifecycle.Event.ON_RESUME) {
                        requestLampProgress()
                    } else if (event == Lifecycle.Event.ON_DESTROY) {
                        mViewModel = null
                        mUserId = null
                        mLifecycle = null
                    }
                }
            })
        }

        setOnSingleClickListener(1000) {

        }
    }

    fun upDataMagicLamp() {
        requestLampProgress()
    }

    private fun requestLampProgress() {
        mUserId?.let {
            mViewModel?.request({ payerService.getLampProgress(it) }, {
                onDataView(it)
            })
        }
    }

    private var nowShowPath = ""
    private fun showFramePag(url: String) {
        if (nowShowPath != url) {
            nowShowPath = url
            val path = FileUtils.getFilePath(FileUtils.getPagFile(), url)
            mBinding.magicLampPag.apply {
                composition = PAGFile.Load(path)
                setRepeatCount(-1)
                if (!isPlaying) {
                    play()
                }
            }
        }

    }

    private fun onDataView(item: PayerLampProgressResp) {
        val lampResources = mapOf(
            0L to Pair(
                com.polaris.live.R.drawable.magic_lamp_btn_copper,
                copper
            ),
            1L to Pair(
                com.polaris.live.R.drawable.magic_lamp_btn_silver,
                silver
            ),
            2L to Pair(
                com.polaris.live.R.drawable.magic_lamp_btn_gold,
                gold
            )
        )

        val (imageRes, pagPath) = lampResources[item.lampType] ?: return

        if (item.progress / item.total.toFloat() > 0.9) {
            mBinding.magicLampPag.visibility = View.GONE
            mBinding.magicLampImg.visibility = View.VISIBLE
            mBinding.magicLampImg.setImageResource(imageRes)

            mLifecycle?.let {
                DownLoadFileUtil.loadPag(it.coroutineScope, pagPath) { downloadedPath, _ ->
                    if (downloadedPath == pagPath) {
                        mBinding.magicLampPag.visibility = View.VISIBLE
                        mBinding.magicLampImg.visibility = View.GONE
                        showFramePag(pagPath)
                    }
                }
            }
        } else {
            mBinding.magicLampPag.visibility = View.GONE
            mBinding.magicLampImg.visibility = View.VISIBLE
            mBinding.magicLampImg.setImageResource(imageRes)
        }
    }


}